package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.SearchArticleVo;
import com.heima.model.search.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.SearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Resource
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;
    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        //异步调用保存历史记录
        ApUser apUser = AppThreadLocalUtil.getApUser();

        apUserSearchService.insert(dto.getSearchWords(),apUser.getId());

        //1.根据条件执行search查询方法
        //1.2创建搜索请求对象，指定索引库名称
        SearchRequest searchRequest=new SearchRequest("app_info_article");
        //1.3封装条件
        BoolQueryBuilder boolQueryBuilder=QueryBuilders.boolQuery();
            //根据关键字查询
        if(dto.getSearchWords()==null){
            boolQueryBuilder.filter(QueryBuilders.matchAllQuery());
        }else{
            boolQueryBuilder.filter(QueryBuilders.matchQuery("all",dto.getSearchWords()));
        }
            //根据时间查询
        if(dto.getMinBehotTime()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }

        searchRequest.source().query(boolQueryBuilder);
            //倒叙展示
        searchRequest.source().sort("publishTime", SortOrder.DESC);
            //分页
        searchRequest.source().from(dto.getPageNum()).size(dto.getPageSize());
            //高亮
        searchRequest.source().highlighter(SearchSourceBuilder.highlight()
                .field("title")//指定高亮的域
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>")
                .requireFieldMatch(false)
        );
        //1.1 调接口
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //2.结果封装
        List<Map> list=new ArrayList<>();//封装数据

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //做高亮设置
                //取出高亮域
            HighlightField highlightField = hit.getHighlightFields().get("title");
            if(highlightField!=null && highlightField.getFragments().length>0){
                Text hightLightTitle = highlightField.getFragments()[0];
                sourceAsMap.put("h_title",hightLightTitle.toString());
            }else{
                sourceAsMap.put("h_title",sourceAsMap.get("title"));
            }
            list.add(sourceAsMap);
        }



        return ResponseResult.okResult(list);
    }

    /**
     * 同步数据到Es中
     *
     * @param vo
     */
    @Override
    public void addArticleToEs(SearchArticleVo vo) {
        //2.创建添加文档请求对象，并指导索引库名称
        IndexRequest indexRequest=new IndexRequest("app_info_article");
        indexRequest.id(vo.getId().toString());//指定添加文档的索引id
        indexRequest.source(JSON.toJSONString(vo), XContentType.JSON);
        //1.调用es的添加文档的api
        try {
            client.index(indexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
